package com.hntky.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hntky.common.Result;
import com.hntky.entity.Sector;
import com.hntky.service.SectorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;


/**
 * @author 周宇轩
 * @date 2023/5/13 11:13
 */
@RestController
@RequestMapping("/sector")
public class SectorController {

    @Autowired
    private SectorService service;

    @GetMapping("/")
    public Result getAllSectorName() {
        return Result.success(service.list());
    }

    /**
     * 分页查询和搜索
     * @param pageNum
     * @param pageSize
     * @param sname
     * @return
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String sname) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("sname", sname);
        return Result.success(service.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
     * 根据科室id查询对应的医生集合
     * @param sid
     * @return
     */
    @GetMapping("/doctors/{sid}")
    public Result doctors(@PathVariable Integer sid) {
        return Result.success(service.findDoctors(sid));
    }

    @GetMapping("/patients/{sid}")
    public Result findPatients(@PathVariable Integer sid){
        return Result.success(service.findPatients(sid));
    }

    @GetMapping("/nurses/{sid}")
    public Result findNurses(@PathVariable Integer sid){
        return Result.success(service.findNurses(sid));
    }

    @GetMapping("/rooms/{sid}")
    public Result findRooms(@PathVariable Integer sid){
        return Result.success(service.findRooms(sid));
    }

    /**
     * 新增科室
     * @param sector
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Sector sector) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("sname", sector.getSname());
        Sector s = service.getOne(queryWrapper);
        // 科室不存在
        if(s == null) {
            return Result.success(service.saveOrUpdate(sector));
        } else {
            return Result.error("500", "该科室已存在");
        }

    }

    /**
     * 删除科室
     * @param sid
     * @return
     */
    @GetMapping("/{sid}")
    public Result del(@PathVariable Integer sid) {
        return Result.success(service.removeById(sid));
    }

    /**
     * 批量删除科室
     * @param ids
     * @return
     */
    @PostMapping("/del/batch")
    public Result delBatch(@RequestBody List<Integer> ids) {
        return Result.success(service.removeBatchByIds(ids));
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库中查询出所有数据
        List<Sector> sectors = service.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
//        writer.addHeaderAlias("sid", "科室编号");
//        writer.addHeaderAlias("sname", "科室姓名");
//        writer.addHeaderAlias("saddr", "科室地址");
//        writer.addHeaderAlias("sphone", "科室电话");
//        writer.addHeaderAlias("sdirector", "科室主任");
        writer.setOnlyAlias(true);

        // 一次性将集合对象写出到excel
        writer.write(sectors, true);

        // 设置浏览器的响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("科室信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }
}
